#include "queue.h"
#include <stdlib.h>
#include <stdio.h>

queue *createQueue() {
    queue *q = malloc(sizeof(queue));
    checkAddress(q);
    q->head = 0;
    q->tail = 0;
    return q;
}

void enqueue(queue *q, int data) {
    node *newNode = malloc(sizeof(node));
    checkAddress(newNode);

    newNode->data = data;
    newNode->next = 0;

    if (q->tail) {
        q->tail->next = newNode;
    } else {
        q->head = newNode;
    }
    q->tail = newNode;
}

void checkAddress(void *ptr) {
    if (ptr == 0) {
        printf("Unable to allocate more memory.\n");
        exit(EXIT_FAILURE);
    }
}

void print_debug(queue *q) {
    printf("QueueLinkedList contents: ");

    node *current = q->head;

    while (current) {
        printf("%d < ", current->data);
        current = current->next;
    }

    printf("\n");
}

int dequeue(queue *q) {
    if (q->head == 0) {
        printf("QueueLinkedList is empty.\n");
        exit(EXIT_FAILURE);
    }
    int value = q->head->data;
    node *tmp = q->head;
    if (q->head->next == 0) {
        q->head = 0;
        q->tail = 0;
    } else {
        q->head = q->head->next;
    }
    free(tmp);
    return value;
}
